package threading;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

class MyThreadPool{
    //阻塞队列用来存放任务，BlockingQueue中指定的元素类型Runnable，也就是任务类型
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    //给队列当中添加任务
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }
    //此处实现一个固定的线程数的线程池
    public MyThreadPool(int n){
        //通过这个for循环创建出n个线程
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(()->{
                try {
                    //此处需要让每个线程内部有个while循环，不停的取任务。
                    while(true){
                        Runnable runnable = queue.take();
                        //
                        runnable.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }

    }
}

public class ThreadDemo25 {
    public static void main(String[] args) throws InterruptedException {
       //创建有10个线程的线程池。
        MyThreadPool pool = new MyThreadPool(10);
        //通过循环给阻塞队列当中添加1000个任务
        for (int i = 0; i < 1000; i++) {
            int number = i;
            pool.submit(new Runnable(){
                @Override
                public void run() {
                    System.out.println("hello "+number);
                }
            });
        }
    }

}
